<template>
    <div v-loading="loading" class="main-container">
        <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
            :http-request="handleUploadRequest">
            <div v-if="localImgUrl.length > 5">
                <!-- 当有图片URL时，显示图片 -->
                <img :src="localImgUrl" />
            </div>
            <div v-else class="uploader-content">
                <el-icon class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
                <span class="upload-text">{{ tips }}</span>
            </div>
        </el-upload>

        <!-- 裁剪弹窗 -->
        <el-dialog append-to-body style="max-width: 420px;" v-model="dialogVisible" title="裁剪" :width="isMobile ? '100%' : '80%'" :fullscreen="isMobile"
            @closed="handleDialogClose" custom-class="cropper-dialog" :close-on-click-modal="false">
            <div class="cropper-wrapper">
                <div class="cropper-container">
                    <img ref="imageRef" :src="imageUrl" alt="待裁剪图片" />
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
                    <el-button type="primary" @click="cropImage" class="confirm-btn">好了!</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import Cropper from "cropperjs";
import { ElDialog, ElButton, ElNotification } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { callApi } from "@/tool/server";
@Options({
    components: {
        ElDialog,
        ElButton,
        Plus,
        ElNotification,
    },
    props: {
        tips: String,
        imgUrl:String,
        width:Number,
        height:Number
    }
})
export default class UploadBodyShow extends Vue {
    tips!: string
    imgUrl!: string
    width!:number
    height!:number
    localImgUrl = '';
    private declare $message: any;
    private cropper: Cropper | null = null;
    private imageUrl = "";
    private dialogVisible = false;
    // private fileInput: HTMLInputElement | null = null;
    private loading = false;
    private store = useStore();
    async mounted() {
        // 组件初始化完成
    }



    // 修改文件选择处理
    private onFileChange(e: Event) {
        const input = e.target as HTMLInputElement;
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = (e) => {
                this.imageUrl = e.target?.result as string;
                this.dialogVisible = true; // 选择文件后才显示弹窗
                this.$nextTick(() => this.initCropper());
            };
            reader.readAsDataURL(input.files[0]);
        }
    }

    // 修改初始化方法
    private initCropper() {
        const image = this.$refs.imageRef as HTMLImageElement;
        if (this.cropper) {
            this.cropper.destroy();
        }
        this.cropper = new Cropper(image, {
            aspectRatio: this.width / this.height,
            viewMode: 1,
            dragMode: "move",
            autoCrop: true,
        });
    }

    // 修改裁剪方法
    private async cropImage() {
        if (!this.cropper) return;
        this.loading = true;
        this.dialogVisible = false; // 上传成功后关闭弹窗

        // 新版需要先获取Canvas元素
        const canvas = this.cropper.getCroppedCanvas({
            width: this.width,
            height: this.height,
        });

        // 添加空值检查
        if (!canvas) {
            ElNotification.error({
                title: "裁剪失败",
                message: "无法获取裁剪画布，请重试",
            });
            this.loading = false;
            return;
        }

        canvas.toBlob(
            async (blob: Blob | null) => {
                if (!blob) return;
                // 生成文件名
                const arrayBuffer = await blob.arrayBuffer();
                const uint8Array = new Uint8Array(arrayBuffer);
                try {
                    callApi("UploadImg", {
                        imgBuf: uint8Array,
                    }).then(async (res) => {
                        if (!res) {
                            return;
                        }
                        this.localImgUrl = res.imgUrl;
                        this.$emit('image-updated', res.imgUrl);
                        ElNotification.success({
                            title: "上传成功",
                            message: `上传成功！前往机器人查看最新形象吧`,
                        });
                        this.loading = false;
                    });
                } catch (error) {
                    console.error("上传失败:", error);
                    ElNotification.error({
                        title: "上传失败",
                        message: "上传失败，请重试",
                    });
                    this.loading = false;
                }
            },
            "image/jpeg",
            0.9
        ); // 添加图片质量参数
    }

    // 修改弹窗关闭处理
    private handleDialogClose() {
        if (this.cropper) {
            this.cropper.destroy();
            this.cropper = null;
        }
        this.imageUrl = "";
    }

    private get isMobile() {
        return window.innerWidth <= 768;
    }

    private beforeAvatarUpload(file: File) {
        const isImage = file.type.startsWith("image/");
        const isLt5M = file.size / 1024 / 1024 < 5;

        if (!isImage) {
            this.$message.error("只能上传图片格式!");
            return false;
        }
        if (!isLt5M) {
            this.$message.error("图片大小不能超过5MB!");
            return false;
        }

        // 触发文件处理
        this.handleFile(file);
        return false; // 禁用自动上传
    }

    private handleFile(file: File) {
        const reader = new FileReader();
        reader.onload = (e) => {
            this.imageUrl = e.target?.result as string;
            this.dialogVisible = true;
            this.$nextTick(() => this.initCropper());
        };
        reader.readAsDataURL(file);
    }

    private handleUploadRequest(request: any) {
        // 处理上传请求的逻辑
    }
}
</script>

<style scoped>
.main-container {
    min-height: 100px;
    display: flex;
    flex-direction: column;
}

.content-wrapper {
    flex: 1;
    display: flex;
    position: relative;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 20px 100px 20px;
}

.uploader-box {
    max-width: 300px;
}

.cropper-wrapper {
    position: relative;
    height: 75vh;
    background: #f8f9fa;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.cropper-container {
    width: 90%;
    height: 90%;
    margin: 2% auto;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cropper-container img {
    max-width: 100%;
    max-height: 80vh;
    object-fit: contain;
}

input[type="file"] {
    margin: 20px 0;
}

button {
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.preview-box {
    margin-top: 30px;
    text-align: center;
}

.preview-box img {
    max-width: 200px;
    max-height: 300px;
    border: 1px solid #ddd;
    margin-top: 10px;
}
:deep(.el-dialog){
    padding: 0;
}
/* 调整弹窗内裁剪区域样式 */
:deep(.el-dialog__body) {
    padding: 10px;
    max-height: 85vh;
    overflow: hidden;
}

/* 移动端全屏样式 */
@media (max-width: 768px) {
    :deep(.cropper-dialog) {
        border-radius: 0;
    }

    .cropper-container {
        width: 100%;
        height: 100%;
        margin: 0 auto;
    }

    :deep(.el-dialog__body) {
        padding: 8px;
        height: calc(100vh - 100px);
    }

    .cropper-container img {
        max-height: 80vh !important;
    }
}

/* 固定弹窗底部按钮 */
:deep(.el-dialog__footer) {
    position: sticky;
    bottom: 0;
    background: white;
    z-index: 1000;
    padding: 5px 20px;
    box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
}

/* 弹窗整体美化 */
:deep(.cropper-dialog) {
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 标题样式优化 */
:deep(.el-dialog__header) {
    border-bottom: 1px solid #eee;
    margin: 0 20px;
    padding: 10px 0;
}

:deep(.el-dialog__title) {
    font-size: 18px;
    color: #333;
    font-weight: 500;
}

/* 底部按钮优化 */
.dialog-footer {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.cancel-btn {
    background: #f0f2f5;
    color: #606266;
    border-color: #dcdfe6;
}

.confirm-btn {
    background: #409eff;
    transition: all 0.3s;
}

.confirm-btn:hover {
    background: #66b1ff;
    transform: translateY(-1px);
}

/* 新增上传区域样式 */
.upload-wrapper {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: calc(100vh - 60px);
}

.upload-btn {
    display: flex;
    flex-direction: column;
    width: 200px;
    height: 200px;
    padding: 30px;
    border: 2px dashed #dcdfe6;
    border-radius: 12px;
    transition: all 0.3s;
}

.upload-btn:hover {
    border-color: #409eff;
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.upload-icon {
    width: 60px;
    height: 60px;
    margin-bottom: 20px;
    color: #606266;
}

.upload-text {
    font-size: 16px;
    color: #606266;
    line-height: 1.5;
}

.avatar-uploader {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100px;
    padding: 20px 0;
}

.uploader-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 20px;
    height: 100%;
}

.avatar {
    width: 300px;
    height: 450px;
    object-fit: cover;
    border-radius: 8px;
}

.avatar-uploader-icon {
    font-size: 48px;
    color: var(--el-color-primary);
    width: 100px;
    height: 100px;
    border: 2px dashed var(--el-border-color);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    background: transparent !important;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
}

.upload-text {
    color: var(--el-text-color-regular);
    font-size: 16px;
}

/* 悬停效果 */
:deep(.avatar-uploader .el-upload) {
    border: none !important;
}

:deep(.avatar-uploader:hover .avatar-uploader-icon) {
    border-color: var(--el-color-primary);
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-upload:focus) {
    outline: none !important;
}

:deep(.el-upload) {
    outline: none !important;
    -webkit-tap-highlight-color: transparent !important;
}

:deep(.el-upload:active) {
    background: transparent !important;
}
</style>